package Fundamental.memory.arrayTest;

public class DateSort {
    public void sort(MyDate[] dates){
        int temp = 0 ;
        for (int i = 0; i < dates.length; i++) {
            temp = i ;
            insert(dates , i , i);
        }
    }
    public void insert(MyDate[] dates , int from , int target){
        // 先找到第一个比 j 小的值
        MyDate temp = null ;
        for(int j = from ; j>=0 ; j--){
            if(dates[j].compare(dates[target]) < 0 ){
                temp = dates[target];
                for(int k = target ; k>j+1 ; k--){
                    swap(dates , k , k-1);
                }
                dates[j+1] = temp;
                break;
            }
            if(j == 0){
                temp = dates[target];
                for (int i = target; i > 0; i--){
                    swap(dates , i-1 , i);
                }
                dates[j] = temp;
            }
        }

    }
   public void swap(MyDate[] dates , int from , int to ){
        dates[to] = dates[from];
    }
    public boolean find(MyDate[] dates , MyDate target){
        int mid =0 ;
        int i = 0 , j = dates.length;
        mid = (i+j)/2;

        while(mid>=0 && mid<=j){

            if(dates[mid].compare(target) > 0){
                j = mid - 1;
                mid = (i+j)/2;
            }else if(dates[mid].compare(target) == 0){
                return true;
            }else {
                i = mid + 1;
                mid = (i+j)/2;
            }
        }
        return false ;
    }
    public static void main(String[] args) {
//        MyDate[] dates = {
//                new MyDate(2020,1,2),
//                new MyDate(2020,1,4),
//                new MyDate(2020,1,1),
//                new MyDate(2020,1,9),
//                new MyDate(2020,1,8),
//        };
        MyDate[] dates = {
                new MyDate(2020,2,3),
                new MyDate(2020,3,3),
                new MyDate(2020,9,3),
                new MyDate(2020,8,3),
                new MyDate(2020,10,3),
        };
        System.out.println("original order:");
        for (MyDate date : dates) {
            System.out.println(date);
        }
        DateSort ds = new DateSort();
        ds.sort(dates);
        System.out.println("ordered:");
        for (MyDate date : dates) {
            System.out.println(date);
        }
        System.out.println("find 2020-01-01:" + ds.find(dates,new MyDate(2020 , 1 ,1)));

    }
}
